<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/17
 * Time: 15:13
 */

namespace app\admin\controller;

use app\admin\Base;
use app\admin\model\Menus;
use app\admin\model\Roles;
use think\Db;

class Menu extends Base
{
    public function index()
    {
        $name = $this->request->param('name', '');
        $status = $this->request->param('status', '');
        $where = [];
        if(!empty($name)){
            $where['name']  = ['like',"%$name%"];
        }
        if($status != ''){
            $where['status'] = $status;
        }
        $model = new Menus();
        $count = $model->where($where)->count();

        $list = $model->field('*')->order('create_time desc')->where($where)->paginate(20);
        if(!empty($list)){
            foreach($list as $k=>$v){
                //后期来优化
                $list[$k]['pids'] = $model->getPids($list[$k]['pids']);
            }
        }
        $page = $list->render();

        return $this->fetch('',compact('count', 'list', 'page'));
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            // 验证
            $validate = validate('app\admin\validate\MenuValidate');
            if (!$validate->check($data)) {
                return ajax_return_adv_error($validate->getError());
            }
            $data['second_pid'] = $data['second_pid'] ?? 0;
            if($data['pid'] == 0){
                $data['pid'] = 0;
                $data['level'] = 1;
                $data['pids'] = "0";
            }

            if($data['pid'] != 0 && $data['second_pid'] == 0){
                $data['level'] = 2;
                $data['pids'] = "0," . $data['pid'];
            }
            if($data['pid'] != 0 && $data['second_pid'] != 0){
                $data['level'] = 3;
                $data['pids'] = "0," . $data['pid'] . "," . $data['second_pid'];
                $data['pid'] = $data['second_pid'];
            }
            //菜单相关数据
            $menu_url = trim($data['menu_url'], '\/') ?? "";
            $model = new Menus();
            if($menu_url != ""){
                //检测menu_url的唯一性
                $exsit_menu_url = $model->where('menu_url', $menu_url)->find();
                if(!empty($exsit_menu_url)){
                    return ajax_return_adv_error("菜单链接已经存在，请更换！");
                }
            }
            $data['icon'] = $data['icon'] ? htmlspecialchars($data['icon']) : htmlspecialchars("&#xe616;");
            $data['menu_url'] = $menu_url;
            $data['order_no'] = $data['order_no'] ?? 1000;
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['update_by'] = parent::$uid;
            unset($data['second_pid']);

            $rs = $model->save($data);
            if(!$rs){
                return ajax_return_adv_error("添加失败");
            }else{
                return ajax_return_adv('添加成功');
            }
        } else {
            // 获取所有顶级菜单
            $model = new Menus();
            $top_menu = $model->getChildMenu();
            return $this->fetch('',compact('top_menu'));
        }
    }

    public function edit()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            // 验证
            $validate = validate('app\admin\validate\MenuValidate');
            if (!$validate->check($data)) {
                return ajax_return_adv_error($validate->getError());
            }
            $data['second_pid'] = $data['second_pid'] ?? 0;
            if($data['pid'] == 0){
                $data['pid'] = 0;
                $data['level'] = 1;
                $data['pids'] = "0";
            }

            if($data['pid'] != 0 && $data['second_pid'] == 0){
                $data['level'] = 2;
                $data['pids'] = "0," . $data['pid'];
            }
            if($data['pid'] != 0 && $data['second_pid'] != 0){
                $data['level'] = 3;
                $data['pids'] = "0," . $data['pid'] . "," . $data['second_pid'];
                $data['pid'] = $data['second_pid'];
            }
            //菜单相关数据
            $menu_url = trim($data['menu_url'], '\/') ?? "";
            $model = new Menus();
            if($menu_url != ""){
                //检测menu_url的唯一性
                $where['menu_url'] = $menu_url;
                $where['id'] = array('neq',$data['id']);
                $exsit_menu_url = $model->where($where)->find();
                if(!empty($exsit_menu_url)){
                    return ajax_return_adv_error("菜单链接已经存在，请更换！");
                }
            }
            $data['icon'] = $data['icon'] ? htmlspecialchars($data['icon']): htmlspecialchars("&#xe616;");
            $data['menu_url'] = $menu_url;
            $data['order_no'] = $data['order_no'] ?? 1000;
            $data['update_time'] = time();
            $data['update_by'] = parent::$uid;
            unset($data['second_pid']);

            $rs = $model->isUpdate(true)->save($data, ['id' => $data['id']]);
            if(!$rs){
                return ajax_return_adv_error("编辑失败");
            }else{
                return ajax_return_adv('编辑成功');
            }
        } else {
            // 获取所有顶级菜单
            $model = new Menus();
            $top_menu = $model->getChildMenu();
            //获取菜单信息
            $id = $this->request->param('id',0);
            if(empty($id)){
                return ajax_return_adv_error("菜单id不能为空");
            }
            $info = $model->get($id);
            //确定第一个select的选中值
            if($info->level == 3){
                $tmp = explode(',', $info->pids);
                $real_pid = $tmp[1];
                //第二个select默认选中值
                $choose_id = $info->pid;
            }else{
                $real_pid = $info->pid;
                $choose_id = 0;
            }
            return $this->fetch('', compact('top_menu', 'info', 'real_pid', 'choose_id'));
        }
    }

    public function delete()
    {
        $id = $this->request->param('id', 0);
        if (empty($id)) {
            return ajax_return_adv_error("菜单id不能为空");
        }

        //如果不是最后一级，就要看是否存在子级菜单，存在则提示要先删子级菜单，才能删除此菜单
        $where[] = ['exp', 'FIND_IN_SET(' . $id . ',pids)'];
        $child_menus = Db::name('menus')->where($where)->select();
        if (!empty($child_menus)) {
            return ajax_return_adv_error("此菜单下面存在子级菜单，必须先删除子级菜单！");
        }

        Db::startTrans();
        try {
            //删除菜单表
            Db::name('menus')->where('id', $id)->delete();

            //删除角色-菜单关系表
            $roles = Db::name('role_menus')->where('menu_id', $id)->column('role_id');
            if (!empty($roles)) {
                //如果存在关联角色，先删除关联关系
                Db::name('role_menus')->where('menu_id', $id)->delete();
                $operatorids = Db::name('role_operators')->whereIn('role_id', $roles)->column('operator_id');
                if (!empty($operatorids)) {
                    //最后把redis缓存存在的管理员权限重新赋值
                    $this->delRoleAndRedis($operatorids);
                }
            }
            // 提交事务
            Db::commit();
            return ajax_return_adv("删除成功");
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ajax_return_adv_error("删除失败");
        }
    }

    /**
     * @todo ajax通过父级id获取二级菜单
     * @pid int 父级id
     * @return string 组合的select
     * 此处也不是最优，php里面最好不要写html代码
    */
    public function ajaxSecondMenu()
    {
        $pid = $this->request->param('pid', 0);
        $choose_id = $this->request->param('choose_id', 0);
        $data = '';
        $msg = '获取成功';
        $code = 200;
        if($pid == 0){
            return ajax_return($data, $msg, $code);
        }
        $model = new Menus();
        $child = $model->getChildMenu($pid);
        $start = '<div class="select-box"><select name="second_pid" class="select" id="second_pid"><option value="0">--请选择--</option>';
        $end = '</select></div>';
        if(empty($child)){
            $data = $start . $end;
            return ajax_return($data, $msg, $code);
        }else{
            $center = '';
            foreach($child as $k=>$v){
                $sel = "";
                if($k == $choose_id){
                    $sel = " selected ";
                }
                $center .= '<option ' . $sel . ' value="' . $k . '">' . $v . '</option>';
            }
            $data = $start . $center . $end;
            return ajax_return($data, $msg, $code);
        }
    }
}